package com.lzx.iteam;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.ApprovalData;
import com.lzx.iteam.bean.DateBean;
import com.lzx.iteam.bean.ScheduleManager;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.widget.selectdate.OnWheelScrollListener;
import com.lzx.iteam.widget.selectdate.WheelView;
import com.lzx.iteam.widget.selectdate.adapter.NumericWheelAdapter;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.RoundImageView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

import static android.R.attr.data;
import static com.lzx.iteam.util.DateUtil.getAppYandMandD;

/**
 * Created by Megan on 16/4/7.
 */
public class ApprovalCreateActivity extends MyBaseActivity implements View.OnClickListener{

    @FindViewById(id = R.id.approval_create_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.ap_create_rl_type)
    private RelativeLayout mRlLeaveType;
    @FindViewById(id = R.id.ap_create_rl_place)
    private RelativeLayout mRlLeavePlace;
    @FindViewById(id = R.id.ap_create_rl_start)
    private RelativeLayout mRlStartTime;
    @FindViewById(id = R.id.ap_create_rl_end)
    private RelativeLayout mRlEndTime;
    @FindViewById(id = R.id.ap_create_rl_days)
    private RelativeLayout mRlDays;
    @FindViewById(id = R.id.ap_create_rl_member)
    private RelativeLayout mRlMember;
    @FindViewById(id = R.id.ap_create_view)
    private View mViewMagin;

    @FindViewById( id = R.id.approval_create_tv_title)
    private TextView mTvTitle;
    @FindViewById( id = R.id.ap_create_tv_type)
    private TextView mTvLeaveType;
    @FindViewById( id = R.id.ap_create_et_place)
    private EditText mEtLeavePlace;
    @FindViewById( id = R.id.ap_create_tv_start_title)
    private TextView mTvStartTitle;
    @FindViewById( id = R.id.ap_create_tv_start)
    private TextView mTvStart;
    @FindViewById( id = R.id.ap_create_tv_end)
    private TextView mTvEnd;
    @FindViewById( id = R.id.ap_create_tv_days)
    private TextView mTvDays;
    @FindViewById( id = R.id.ap_create_day)
    private TextView mTvOutDay;
    @FindViewById( id = R.id.ap_create_tv_reason)
    private TextView mTvReason;
    @FindViewById( id = R.id.ap_create_et_reason)
    private EditText mEtReason;
    @FindViewById( id = R.id.ap_create_tv_submit)
    private TextView mTvSubmit;
    @FindViewById( id = R.id.ap_create_tv_member)
    private TextView mTvMember;
    @FindViewById( id = R.id.ap_admin_iv_head)
    private RoundImageView mIvMember;


    private AlertDialog mDialogReason;
    private WheelView year;
    private WheelView month;
    private WheelView day;
    private WheelView morning_After;
    private HashMap<Long,DateBean> mSelectMapDates = new HashMap<>();
    private ArrayList<ArrayList<DateBean>> mTimeData = new ArrayList<>();
    private ArrayList<DateBean> mSelectDate = new ArrayList<>();
    private SizeComparator mComparator;
    private ApprovalData mApData;

    private Calendar c;
    private int curYear;
    private int curMonth;
    private int curDate;
    private int mStartMonth,mEndMonth;
    private int mStartDay,mEndDay;

    private long mOneDayTime = 24 * 60 * 60; // 一天的秒数
    private long mStartDate;    // 开始时间戳
    private int mStartpart;     // 开始上下午  1：上午 2：下午
    private long mEndDate;      // 结束时间戳
    private int mEndPart;       // 结束上下午  1：上午 2：下午
    private float mOutDays;
    private String mLeaveReason;
    private String mTravelPlace;
    private String mApprovalName;    // 审批类型名称
    private int mApprovalType = -1;  // 审批类型  1.出差，2.请假，3.外出，4.签到
    private int mLeaveType = -1;     // 请假类型  0.事假，1.病假，2.年假，3.婚假，4.产假
    private String mLeaderImage;
    private String mLeaderUid;
    private String mAttenCalendarId;  // 考勤日历ID
    private String mAttenRecordId;    // 考勤记录ID
    private String[] mDayPart = {"","上午","下午"};

    public static final int SELECT_LEADER_REQUESTCODE = 30001;
    public static final int CREATE_APPROVAL = 30002;
    public static final int SELECT_DATE = 30003;


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case CREATE_APPROVAL:
                    waitDlgDismiss();
                    if (msg.arg1 == 0){
                        showShortToast("创建成功");
                        finish();
                    }else{
                        showShortToast((String) msg.obj);
                    }
                    break;
            }
        }
    };




    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState,R.layout.approval_create_layout);
    }

    @Override
    public void initListener() {

        mLayoutBack.setOnClickListener(this);
        mRlLeaveType.setOnClickListener(this);
        mRlStartTime.setOnClickListener(this);
        mRlEndTime.setOnClickListener(this);
        mRlMember.setOnClickListener(this);
        mTvSubmit.setOnClickListener(this);

    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        String action = intent.getAction();
        if ("attendance_to_approval".equals(action)){
            mRlStartTime.setEnabled(false);
            mAttenRecordId = intent.getStringExtra("atten_record_id");
            mAttenCalendarId = intent.getStringExtra("atten_calendar_id");
        }else if ("create_approval".equals(action)){
            mRlStartTime.setEnabled(true);
        }
        mApData = (ApprovalData) intent.getSerializableExtra("approvalData");
        if (mApData != null){
            mApprovalType = mApData.getApproval_type();
            String time = mApData.getApproval_start_time();
            if (!StringUtil.isEmpty(time)){
                mStartDate = Long.parseLong(mApData.getApproval_start_time());
                mStartpart = mApData.getApproval_start_part();
            }
        }
        // TODO 设置头像圆角
        mIvMember.setRectAdius(Constants.dip2px(mActivity,18));
        setData();
        c = Calendar.getInstance();
        curYear = c.get(Calendar.YEAR);
        curMonth = c.get(Calendar.MONTH) + 1; //通过Calendar算出的月数要+1
        curDate = c.get(Calendar.DATE);

        mComparator = new SizeComparator();

    }

    private void setData(){
        switch (mApprovalType){
            case 1:
                mApprovalName = "出差";
                mTvTitle.setText("出差申请");
                mRlLeavePlace.setVisibility(View.VISIBLE);
                mTravelPlace = mApData.getApproval_address();
                if (!StringUtil.isEmpty(mTravelPlace)){
                    mEtLeavePlace.setText(mTravelPlace);
                }
                mTvStartTitle.setText("出差时间");
                mTvDays.setText("出差天数");
                mTvReason.setText("出差事由");
                mEtReason.setHint("请输入出差的理由");
                break;
            case 2:
                mApprovalName = "请假";
                mTvTitle.setText("请假申请");
                mRlLeaveType.setVisibility(View.VISIBLE);
                mTvStartTitle.setText("请假时间");
                mTvReason.setText("请假事由");
                mEtReason.setHint("请输入请假的理由");
                break;
            case 3:
                mApprovalName = "外出";
                mTvTitle.setText("外出申请");
                mTvStartTitle.setText("外出时间");
                mTvDays.setText("外出天数");
                mTvReason.setText("外出事由");
                mEtReason.setHint("请输入外出的理由");
                break;
            case 4:
                mApprovalName = "申诉";
                mTvStartTitle.setText("签到异常时间");
                mTvTitle.setText("签到申诉");
                mRlDays.setVisibility(View.GONE);
                mViewMagin.setVisibility(View.VISIBLE);
                mRlDays.setVisibility(View.GONE);
                mTvReason.setText("签到异常原因");
                mEtReason.setHint("请输入申诉的理由");
                break;
        }

        if (mStartDate != 0){
            mStartMonth = DateUtil.getMonth(mStartDate * 1000);
            mStartDay = DateUtil.getDay(mStartDate * 1000);
            mStartpart = mApData.getApproval_start_part();
            String M_a = mStartpart == 1 ?" 上午":" 下午";
            mTvStart.setText(DateUtil.formatDate(mStartDate * 1000) + M_a);
        }

    }


    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.approval_create_ll_back:
                finish();
                break;
            case R.id.ap_create_rl_start:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Intent date = new Intent(mActivity,SelectDateActivity.class);
                date.putExtra("group_id",mApData.getApproval_group_id());
                date.putExtra("select_date",mSelectMapDates);
                date.putExtra("approval_type",mApprovalType);
                startActivityForResult(date,SELECT_DATE);
                break;
            case R.id.ap_create_rl_end:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (mStartDate == 0){
                    showShortToast("请先选择开始时间");
                }else{
                    showMorningAndAfter(false);
                }
                break;
            case R.id.ap_create_rl_type:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showReasonDialog();
                break;
            case R.id.ap_create_rl_member:
                Intent choose = new Intent(mActivity,ScheduleManagerActivity.class);
                choose.setAction("approval_leader_select");
                choose.putExtra("group_id",mApData.getApproval_group_id());
                startActivityForResult(choose,SELECT_LEADER_REQUESTCODE);
                break;
            case R.id.ap_create_tv_submit:
                int check = checkMessage();
                if (check == 1){
                    waitDlgShow();
                    createApproval();
                }
                break;
            case R.id.ap_reason_1:
                mTvLeaveType.setText(getString(R.string.ap_reason_1));
                mLeaveType = 0;
                mDialogReason.dismiss();
                break;
            case R.id.ap_reason_2:
                mTvLeaveType.setText(getString(R.string.ap_reason_2));
                mLeaveType = 1;
                mDialogReason.dismiss();
                break;
            case R.id.ap_reason_3:
                mTvLeaveType.setText(getString(R.string.ap_reason_3));
                mLeaveType = 2;
                mDialogReason.dismiss();
                break;
            case R.id.ap_reason_4:
                mTvLeaveType.setText(getString(R.string.ap_reason_4));
                mLeaveType = 3;
                mDialogReason.dismiss();
                break;
            case R.id.ap_reason_5:
                mTvLeaveType.setText(getString(R.string.ap_reason_5));
                mLeaveType = 4;
                mDialogReason.dismiss();
                break;
            case R.id.ap_reason_cancle:
                mDialogReason.dismiss();
                break;
            case R.id.view_cancel:
                mDialogReason.dismiss();
                break;
        }
    }

    /**
     * 显示请假理由
     */
    private void showReasonDialog() {

        mDialogReason = new AlertDialog.Builder(mActivity)
                .create();
        mDialogReason.show();
        Window window = mDialogReason.getWindow();
        WindowManager.LayoutParams lp = mDialogReason.getWindow().getAttributes();
        lp.dimAmount = 0.3f; // TODO 设置黑暗度  0.0f完全不暗，1.0f全暗
//        lp.alpha = 0.5f; // TODO 设置透明度    0.0f完全透明，1.0完全不透明
        window.setAttributes(lp);
        // 设置布局
        window.setContentView(R.layout.approval_reason_layout);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.bottomStyle);

        TextView reason1 = (TextView) window.findViewById(R.id.ap_reason_1);
        TextView reason2 = (TextView) window.findViewById(R.id.ap_reason_2);
        TextView reason3 = (TextView) window.findViewById(R.id.ap_reason_3);
        TextView reason4 = (TextView) window.findViewById(R.id.ap_reason_4);
        TextView reason5 = (TextView) window.findViewById(R.id.ap_reason_5);
        TextView cancel = (TextView) window.findViewById(R.id.ap_reason_cancle);
        LinearLayout cancelLayout = (LinearLayout) window.findViewById(R.id.view_cancel);
        reason1.setOnClickListener(this);
        reason2.setOnClickListener(this);
        reason3.setOnClickListener(this);
        reason4.setOnClickListener(this);
        reason5.setOnClickListener(this);
        cancel.setOnClickListener(this);
        cancelLayout.setOnClickListener(this);

    }

    private int checkMessage(){
        mTravelPlace = mEtLeavePlace.getText().toString().trim();
//        String leaveDays = mEtDays.getText().toString().trim();
        mLeaveReason = mEtReason.getText().toString().trim();

        switch (mApprovalType){
            case 1:
                if (StringUtil.isEmpty(mTravelPlace)){
                    showShortToast("请填写出差地点");
                    return -1;
                }
                break;
            case 2:
                if (mLeaveType == -1){
                    showShortToast("请选择请假类型");
                    return -1;
                }
                break;
            case 3:

                break;
            case 4:
                break;
        }
        if (mApprovalType != 4 && (mSelectDate == null || (mSelectDate != null && mSelectDate.size() == 0))){
            showShortToast("请选择" + mApprovalName + "时间");
            return -1;
        }
        /*if (mStartDate == 0){
            showShortToast("请选择开始时间");
            return -1;
        }
        if (mEndDate == 0 && mApprovalType != 4){
            showShortToast("请选择结束时间");
            return -1;
        }
        if ( mApprovalType != 4){
            if (StringUtil.isEmpty(leaveDays) ){
                showShortToast("请填写" + mApprovalName + "的天数");
                return -1;
            }else{
                mLeaveDays = Float.parseFloat(leaveDays);
                Log.d("天数+时长","天数 == " + mLeaveDays);
                if (mLeaveDays%0.5 != 0){
                    showShortToast("天数最小单位是0.5");
                    return -1;
                }else{
                    Log.d("天数+时长","正确");
                }

            }
        }*/

        if (StringUtil.isEmpty(mLeaveReason)){
            showShortToast("请填写" + mApprovalName + "的理由");
            return -1;
        }
        if (StringUtil.isEmpty(mLeaderUid)){
            showShortToast("请选择审批人");
            return -1;
        }
        return 1;
    }

    /**
     * 创建审批
     */
    private void createApproval(){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_GROUP_ID, mApData.getApproval_group_id()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_REASON, mLeaveReason));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVE_ADMIN, mLeaderUid));

        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(CREATE_APPROVAL));
        if (mApprovalType != 4){
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROCAL_TYPE, mApprovalType + ""));

            /*nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_START_TIME, mStartDate + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_START_PART, mStartpart + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_END_TIME, mEndDate + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_END_PART, mEndPart + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_DAY, mLeaveDays + ""));*/

            JSONArray array = new JSONArray();
            for (int i = 0; i < mSelectDate.size(); i++) {
                DateBean bean = mSelectDate.get(i);
                JSONObject obj = new JSONObject();
                try {
                    obj.put("part",bean.getPart());
                    obj.put("time",bean.getTime());
                    array.put(obj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_DATES, array.toString()));
            if (mApprovalType == 1){  // 出差地址
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_ADDRESS, mTravelPlace));
            }else if (mApprovalType == 2){ // 请假类型
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_LEAVE_TYPE, mLeaveType + ""));
            }
            msg.mApi = AsynHttpClient.API_EVENT_APPROVAL_NEW;
        }else{
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_ATTEN_RECORD_ID, mAttenRecordId));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_ATTEN_CALENDAR_ID, mAttenCalendarId));
            msg.mApi = AsynHttpClient.API_EVENT_APPROVAL_ATTEN_STATE;
        }

        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }


    /**
     * 时间选择
     * @param isStart  true：开始时间  false：结束时间
     * 需求：  1、外出选开始时间，结束时间默认选上，且只能选同一天
     *        2、签到申诉时间只能选当天之前，如果是考勤页面跳转过来的时间不可选择是传过来的
     *
     */
    private void showMorningAndAfter(final boolean isStart) {

        final AlertDialog dialog = new AlertDialog.Builder(mActivity)
                .create();
        dialog.show();
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.dimAmount = 0.3f; // TODO 设置黑暗度  0.0f完全不暗，1.0f全暗
//        lp.alpha = 0.5f; // TODO 设置透明度    0.0f完全透明，1.0完全不透明
        window.setAttributes(lp);
        // 设置布局
        window.setContentView(R.layout.ap_date_layout);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.bottomStyle);


        year = (WheelView) window.findViewById(R.id.new_year);
        initYear(year,curYear);
        month = (WheelView) window.findViewById(R.id.new_month);
        initMonth(month);
        day = (WheelView) window.findViewById(R.id.new_day);
        initDay(day,curYear, curMonth);
        morning_After = (WheelView) window.findViewById(R.id.new_m_a);
        initRain(morning_After);

        // 设置当前时间
        year.setCurrentItem(0);
        if (isStart){
            if (mStartMonth != 0){
                month.setCurrentItem(mStartMonth - 1);
            }else{
                month.setCurrentItem(curMonth - 1);
            }
            if (mStartDay != 0){
                day.setCurrentItem(mStartDay - 1);
            }else{
                day.setCurrentItem(curDate - 1);
            }
            if (mStartpart != 0){
                morning_After.setCurrentItem(mStartpart -1);
            }else{
                morning_After.setCurrentItem(0);
            }

        }else{
            if (mEndMonth != 0){
                month.setCurrentItem(mEndMonth - 1);
            }else{
                month.setCurrentItem(curMonth - 1);
            }
            if (mEndDay != 0){
                day.setCurrentItem(mEndDay - 1);
            }else{
                day.setCurrentItem(curDate - 1);
            }
            if (mEndPart != 0){
                morning_After.setCurrentItem(mEndPart -1);
            }else{
                if (mApprovalType == 1 || mApprovalType == 2){
                    mEndPart = 2;
                    morning_After.setCurrentItem(1);
                }else{
                    morning_After.setCurrentItem(0);
                }
            }
        }


        // 设置监听
        TextView ok = (TextView) window.findViewById(R.id.new_set);
        TextView cancel = (TextView) window.findViewById(R.id.new_cancel);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int index = morning_After.getCurrentItem();
                String m_a = index == 0 ? " 上午":" 下午";
                if(isStart){
                    int sMonth = month.getCurrentItem() + 1;
                    int sDay = day.getCurrentItem() + 1;
                    if (mApprovalType == 4 && (sMonth > curMonth || (sMonth == curMonth && sDay > curDate))){
                        showShortToast("申诉时间不能超过今天，请重新选择");
                    }else{
                        mStartMonth = month.getCurrentItem() + 1;
                        mStartDay = day.getCurrentItem() + 1;
                        c.set(curYear, mStartMonth - 1, mStartDay, 00, 00, 00);
                        mStartDate = c.getTimeInMillis()/1000;
                        mTvStart.setText(DateUtil.formatDate(mStartDate*1000) + m_a);
                        mStartpart = index + 1;
                        if (mApprovalType == 3){
                            mEndMonth = mStartMonth;
                            mEndDay = mStartDay;
                            mEndPart = mStartpart;
                            mEndDate = mStartDate;
                            mTvEnd.setText(DateUtil.getDate(mEndDate*1000) + m_a);
                            mTvOutDay.setText("0.5");
                        }

                    }

                }else{
                    int sMonth = month.getCurrentItem() + 1;
                    int sDay = day.getCurrentItem() + 1;
                    c.set(curYear, sMonth - 1, sDay, 00, 00, 00);
                    long end = c.getTimeInMillis()/1000;
                    int part = index + 1;
                    if (mApprovalType == 3 && (mStartMonth != sMonth || mStartDay != sDay)){
                        showShortToast("外出时长不能跨天，请重新选择");
                        dialog.cancel();
                        return;
                    }
                    if (end < mStartDate || (end == mStartDate && mStartpart > part)){
                        showShortToast("结束时间小于开始时间，请重新选择");
                    }else{
                        mEndMonth = sMonth;
                        mEndDay = sDay;
                        mEndDate = end;
                        mTvEnd.setText(DateUtil.getDate(mEndDate*1000) + m_a);
                        mEndPart = part;
                        if (mApprovalType == 3){
                            if (mStartpart == mEndPart){
                                mTvOutDay.setText("0.5");
                            }else{
                                mTvOutDay.setText("1");
                            }
                        }
                    }
                }
                dialog.cancel();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.cancel();
            }
        });
        LinearLayout cancelLayout = (LinearLayout) window.findViewById(R.id.view_cancel);
        cancelLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                dialog.cancel();
                return false;
            }
        });
    }


    /**
     * 初始化年
     */
    private void initYear(WheelView wheelView,int curYear) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, curYear, curYear);
        numericWheelAdapter.setLabel(" 年");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        wheelView.setViewAdapter(numericWheelAdapter);
        wheelView.setCyclic(false);
    }

    /**
     * 初始化月
     */
    private void initMonth(WheelView wheelView) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 1, 12, "%02d");
        numericWheelAdapter.setLabel(" 月");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        wheelView.setViewAdapter(numericWheelAdapter);
        wheelView.setCyclic(true);
        wheelView.addScrollingListener(scrollListener);
    }
    /**
     * 初始化天
     */
    private void initDay(WheelView wheelView,int arg1, int arg2) {
        int count = Constants.getDay(arg1, arg2);
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 1, count, "%02d");
        numericWheelAdapter.setLabel(" 日");
        //		numericWheelAdapter.setTextSize(15);  设置字体大小
        wheelView.setViewAdapter(numericWheelAdapter);
        wheelView.setCyclic(true);
        // TODO 如果之前选择的日期大于这个月的天数 置为第一天
        if (wheelView.getCurrentItem() + 1 > count){
            wheelView.setCurrentItem(0);
        }
    }

    /**
     * 初始化上下午
     * @param wheelView
     */
    private void initRain(WheelView wheelView) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this, 0, 1);
        wheelView.setViewAdapter(numericWheelAdapter);
        wheelView.setCyclic(false);
    }

    /**
     * 当年份或者月份滑动结束时要更新 天数
     */
    OnWheelScrollListener scrollListener = new OnWheelScrollListener() {

        @Override
        public void onScrollingStarted(WheelView wheel) {

        }

        @Override
        public void onScrollingFinished(WheelView wheel) {
            // TODO Auto-generated method stub
            int n_year = curYear;
            int n_month = month.getCurrentItem() + 1;
            initDay(day,n_year, n_month);
        }
    };


    @Override
    protected void onDestroy() {
        ScheduleManagerActivity.mSelectPosition = -1;
        super.onDestroy();
    }

    private void getSelectDate(){

        mSelectDate.clear();
        Iterator iter = mSelectMapDates.keySet().iterator();
        while (iter.hasNext()){
            Object key = iter.next();
            DateBean bean = mSelectMapDates.get(key);
            mSelectDate.add(bean);
        }

        Collections.sort(mSelectDate, mComparator);
        mTimeData.clear();
        mOutDays = 0;
        for (int i = 0; i < mSelectDate.size(); i++) {

            DateBean curBean = mSelectDate.get(i);
            int part = curBean.getPart();
            switch (part){
                case 0:
                    mOutDays += 1;
                    break;
                case 1:
                case 2:
                    mOutDays += 0.5f;
                    break;
                default:
                    break;
            }

            if (i == 0){
                ArrayList<DateBean> time = new ArrayList<>();
                time.add(curBean);
                mTimeData.add(time);
            }else{
                DateBean lastBean = mSelectDate.get(i - 1);
                if ((curBean.getTime() - lastBean.getTime()) == mOneDayTime && lastBean.getPart() == 0 && curBean.getPart() == 0){
                    mTimeData.get(mTimeData.size() - 1).add(curBean);
                }else{
                    ArrayList<DateBean> time = new ArrayList<>();
                    time.add(mSelectDate.get(i));
                    mTimeData.add(time);
                }
            }

        }

        mTvStart.setText(setTimeShow());
        mTvOutDay.setText(mOutDays + "");
    }

    private String setTimeShow(){
        StringBuilder selectTime = new StringBuilder();
        for (int i = 0; i < mTimeData.size(); i++) {
            ArrayList<DateBean> time = mTimeData.get(i);
            String str = "";
            if (time.size() > 0){
                if (time.size() == 1){
                    str = getAppYandMandD(time.get(0).getTime() * 1000) + mDayPart[time.get(0).getPart()] ;
                }else{
                    long time1 = time.get(0).getTime();
                    long time2 = time.get(time.size() -1).getTime();
                    if (DateUtil.getYear(time1 * 1000) == DateUtil.getYear(time2 * 1000)){
                        str =  getAppYandMandD(time1 * 1000) + " - " + DateUtil.getAppMandD(time2 * 1000);
                    }else{
                        str =  getAppYandMandD(time1 * 1000) + " - " + getAppYandMandD(time2 * 1000);
                    }
                }
            }
            if(i == mTimeData.size() -1){
                selectTime.append(str);
            }else{
                selectTime.append(str + "\n");
            }
        }
        return selectTime.toString();

    }

    /**
     *实现Comparator接口类
     */
    public class SizeComparator implements Comparator<DateBean> {
        @Override
        public int compare(DateBean arg0, DateBean arg1) {
            // jdk 1.7以后（包括1.7）返回相反数才行
            if(arg0.getTime() > arg1.getTime()){
                return 1;
            }
            return -1;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case SELECT_LEADER_REQUESTCODE:
                    ScheduleManager leader = (ScheduleManager) data.getSerializableExtra("leader");
                    if (leader != null){
                        mLeaderUid = leader.getUserId();
                        mLeaderImage = leader.getAvatar();
                        ImageLoaderInterface.imageLoader.displayImage(mLeaderImage,mIvMember,ImageLoaderInterface.optionHeadImage);
                        mTvMember.setVisibility(View.GONE);
                    }
                    Log.d("leader_msg"," leader_msg == " + mLeaderUid + mLeaderImage);
                    break;
                case SELECT_DATE:
                    mSelectMapDates = (HashMap<Long, DateBean>) data.getSerializableExtra("select_date");
                    if (mSelectMapDates != null){
                        getSelectDate();
                    }
                    break;

            }
        }else{
            if (StringUtil.isEmpty(mLeaderUid)){
                ScheduleManagerActivity.mSelectPosition = -1;
            }
        }
    }
}
